import lodash from 'lodash'
import axios from 'axios'
import NProgress from 'nprogress'
// import xhr from '@http/http'
import { Message } from 'element-ui'
export function _isType (t) {
  return Object.prototype.toString
    .call(t)
    .slice(8, -1)
    .toLowerCase()
}

export function _saveLocalStorage (key, value) {
  if (_isType(value) === 'string') {
    localStorage.setItem(key, value)
  } else {
    let Info = JSON.stringify(value)
    localStorage.setItem(key, Info)
  }
}

export function _getLocalStorage (item) {
  return localStorage.getItem(item)
}

export function _clearStorage () {
  localStorage.clear()
}

export function _getCookie (cName) {
  let cStart, cEnd
  if (document.cookie.length > 0) {
    cStart = document.cookie.indexOf(cName + '=')
    if (cStart !== -1) {
      cStart = cStart + cName.length + 1
      cEnd = document.cookie.indexOf(';', cStart)
      if (cEnd === -1) cEnd = document.cookie.length
      return document.cookie.slice(cStart, cEnd)
    }
  }
  return ''
}

export function _keyMirror (obj) {
  if (obj instanceof Object) {
    var _obj = Object.assign({}, obj)
    var _keyArray = Object.keys(obj)
    _keyArray.forEach(key => {
      _obj[key] = key
      return true
    })
    return _obj
  }
}

export function _isArrayFn (value) {
  if (typeof Array.isArray === 'function') {
    return Array.isArray(value)
  } else {
    return Object.prototype.toString.call(value) === '[object Array]'
  }
}

export function _pagination (pageNo, pageSize, array) {
  let offset = (pageNo - 1) * pageSize
  return offset + pageSize >= array.length
    ? array.slice(offset, array.length)
    : array.slice(offset, offset + pageSize)
}
export function transSexUnknow (num) {
  let res = ''
  switch (Number(num)) {
    case 2:
      res = '女'
      break
    case 1:
      res = '男'
      break
    case 0:
      res = '未知'
      break
    default:
      res = '未知'
  }
  return res
}
export function transSex (num) {
  let res = ''
  switch (Number(num)) {
    case 2:
      res = '女'
      break
    case 1:
      res = '男'
      break
    case 0:
      res = '不限'
      break
    default:
      res = '未知'
  }
  return res
}
export function sexTrans (num) {
  let res = null
  switch (num) {
    case '女':
      res = 2
      break
    case '男':
      res = 1
      break
    case '不限':
      res = 0
      break
    default:
      res = null
  }
  return res
}
export function transIs (num) {
  let res = ''
  num ? (res = '是') : (res = '否')
  return res
}
export function transType (num) {
  let res = ''
  switch (Number(num)) {
    case 2:
      res = '调宿'
      break
    case 1:
      res = '入住'
      break
    case 0:
      res = '退宿'
      break
  }
  return res
}
// 映射审核状态
export const transStatus = status => {
  let transStatus = ''
  switch (status) {
    case 1:
      transStatus = '审核中'
      break
    case 3:
      transStatus = '驳回'
      break
    case 2:
      transStatus = '审批通过'
      break
    case 4:
      transStatus = '已撤回'
      break
  }
  return transStatus
}
export const transUser = user => {
  let transUser = ''
  switch (user.initiator) {
    case 1:
      transUser = `${user.initiatorName}（学生）`
      break
    case 13:
      transUser = `${user.initiatorName}（咨询师助理）`
      break
    case 15:
      transUser = `${user.initiatorName}（管理教师）`
      break
    default:
      transUser = ''
  }
  return transUser
}
export let addProperty = (arr, obj) => {
  arr.forEach(item => {
    item = lodash.merge(item, obj)
  })
  return arr
}
export function downExl (url, fileName, isAbsolute) {
  if (url) {
    let a = null
    if (document.getElementById('downLoad')) {
      a = document.getElementById('downLoad')
      a.download = fileName || ''
      a.href = isAbsolute ? `/${url}` : `.././${url}`
      a.click()
    } else {
      a = document.createElement('a')
      a.id = 'downLoad'
      a.download = fileName
      a.href = isAbsolute ? `/${url}` : `.././${url}`
      a.style.position = 'absolute'
      document.body.appendChild(a)
      a.click()
    }
  } else {
    Message.error('导出错误')
  }
}
// 导出文件流
export function exportFile (url, body, fileName) {
  axios.defaults.baseURL = process.env.BASE_URL
  axios({
    url,
    method: 'post',
    data: body,
    responseType: 'blob'
  }).then(res => {
    if (res.headers['error_message']) {
      const message = decodeURI(res.headers['error_message']) // 解决中文乱码问题
      Message.error(message)
    } else {
      var blob = res.data
      var reader = new FileReader()
      reader.readAsDataURL(blob)
      if (window.navigator.msSaveOrOpenBlob) {
        // 兼容IE10及以上
        navigator.msSaveBlob(blob, fileName || `导出信息.xls`)
      } else {
        reader.onload = function (e) {
          let a = null
          if (document.getElementById('downLoad')) {
            a = document.getElementById('downLoad')
            a.href = e.target.result
            a.download = fileName || `导出信息.xls`
            a.click()
          } else {
            a = document.createElement('a')
            a.id = 'downLoad'
            a.href = e.target.result
            a.download = fileName || `导出信息.xls`
            // Message({type: 'success', message: '开始下载'})
            a.style.position = 'absolute'
            document.body.appendChild(a)
            a.click()
          }
        }
      }
    }
    NProgress.done()
  })
}
// 导出文件流
export function handleBlob (blob, fileName) {
  var reader = new FileReader()
  reader.readAsDataURL(blob)
  reader.onload = function (e) {
    // 转换完成，创建一个a标签用于下载
    const a = document.createElement('a')
    document.body.appendChild(a)
    a.href = e.target.result
    a.download = fileName || '名单导入模板.xls'
    a.id = 'downLoad'
    a.click()
    a.remove()
  }
}
// 制保留2位小数，如：2，会在2后面补上00.即2.00
export function toDecimal (x) {
  var f = parseFloat(x)
  if (isNaN(f)) {
    return false
  }
  f = Math.round(x * 100) / 100
  var s = f.toString()
  var rs = s.indexOf('.')
  if (rs < 0) {
    rs = s.length
    s += '.'
  }
  while (s.length <= rs + 2) {
    s += '0'
  }
  return s.toFixed(2)
}
